/**
 * 
 */
package br.com.ac.fatureweb.rest.service;

import javax.inject.Inject;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import br.com.ac.fatureweb.exception.AccessNaoAutorizadoException;
import br.com.ac.fatureweb.integration.model.EquipamentoVO;
import br.com.ac.fatureweb.integration.model.LeituristaVO;
import br.com.ac.fatureweb.service.NgcEquipamentoBean;
import br.com.ac.fatureweb.service.NgcLeituristaBean;
import br.com.ac.fatureweb.service.ValidarAcesso;

/**
 * @author aldivone
 *
 */
@Path("/autenticationBean")
public class AutenticationBean {

	@Inject
	private NgcLeituristaBean ngcLeituristaBean;

	@Inject
	private NgcEquipamentoBean ngcEquipamentoBean;

	@GET
	@Path("ping")
	@Produces(MediaType.APPLICATION_JSON)
	public Response ping() {
		try {
			Thread.sleep(1000);

			return Response.ok().entity(true).build();
		} catch (final Exception e) {
			return Response.status(Status.INTERNAL_SERVER_ERROR)
					.entity(e.getMessage()).build();
		}
	}

	@POST
	@Path("buscarEquipamento")
	@Produces(MediaType.APPLICATION_JSON)
	public Response buscarEquipamento(

	@FormParam("imei") final String imei,

	@FormParam("usuario") final Long usuario,

	@FormParam("senha") final String senha) {
		try {
			if (ValidarAcesso.execute(usuario, senha, imei, ngcLeituristaBean)) {

				EquipamentoVO equipamentoVO = ngcEquipamentoBean
						.buscarEquipamento(imei);

				return Response.ok().entity(equipamentoVO).build();
			}

			return Response.status(Status.NO_CONTENT).build();
		} catch (AccessNaoAutorizadoException anae) {
			return Response.status(Status.UNAUTHORIZED)
					.entity(anae.getMessage()).build();
		} catch (final Exception e) {
			return Response.status(Status.INTERNAL_SERVER_ERROR)
					.entity(e.getMessage()).build();
		}
	}

	/**
	 * Buscar as informações de um usuário informado, desde que o mesmo passe na
	 * validação de acesso.
	 * 
	 * @param imei
	 * @param usuario
	 * @param senha
	 * @return
	 */
	@POST
	@Path("buscarUsuarioMobile")
	@Produces(MediaType.APPLICATION_JSON)
	public Response buscarUsuarioMobile(

	@FormParam("imei") final String imei,

	@FormParam("usuario") final Long usuario,

	@FormParam("senha") final String senha) {
		try {
			if (ValidarAcesso.execute(usuario, senha, imei, ngcLeituristaBean)) {
				LeituristaVO leituristaVO = ngcLeituristaBean
						.buscarUsuarioMobile(usuario);

				return Response.ok().entity(leituristaVO).build();
			}

			return Response.status(Status.NO_CONTENT).build();

		} catch (AccessNaoAutorizadoException anae) {
			return Response.status(Status.UNAUTHORIZED)
					.entity(anae.getMessage()).build();
		} catch (final Exception e) {
			return Response.status(Status.INTERNAL_SERVER_ERROR)
					.entity(e.getMessage()).build();
		}
	}

}
